//
//  CLDocModel.m
//  chanlin
//
//  Created by Ryan on 14-11-10.
//  Copyright (c) 2014年 chanlin. All rights reserved.
//

#import "CLDocModel.h"
#import "SgrGCD.h"
#import "IFCoreDataManager.h"
#import "CLItemDetail.h"
#import "NSObject+sagittarius.h"
#import "CLGloble.h"
#import "CLHtmlExtracter.h"
#import "INHtmlElement.h"
#import "IFLabel2.h"
#import "INHtmlElementUtil.h"
#import "NSString+Filter.h"


#define I_DOC_TEXT_MARGIN_SPACE IFScreenFit2(11.f,13.f)
#define I_DOC_CONTENT_WIDTH (GlobleWidth-(2*I_DOC_TEXT_MARGIN_SPACE))

#define IMAGE_HEIGHT_DEFAULT IFScreenFit2s((183.f/290.f)*(I_DOC_CONTENT_WIDTH))

@implementation IFDocTemplate

SGR_DEF_SINGLETION(IFDocTemplate)

- (instancetype)init{
    self=[super init];
    if(self){
        
        
        
        
        NSString *html=[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"docTemplate" ofType:@"html"]
                                                 encoding:NSUTF8StringEncoding
                                                    error:nil];
        NSString *finishLog=@"doc_finish_logoIcon.png";
        
        self.htmlTemplate=
        [NSString stringWithFormat:html,[self divContengClass],[self noteClass],IFScreenFit2s(15.f),IFScreenFit2s(15.f),finishLog];
        
        self.headImg=@"<div id=\"top_banner\" style=\"height:%fpx; width:%fpx;\">\
        #nbsp;\
        </div>";
        
        self.up_comment=@"<a><img src=\"doc_commentCount_icon.png\" class=\"comm_img\" />%@</a>";
        
        self.title=@"<div class=\"title title_frame\">%@</div>";
        
        self.time_source=@"<div class=\"time_and_source time_and_source_frame\">\
        <span class=\"time\" id=\"time\">%@</span>&nbsp;&nbsp;<span class=\"source\" id=\"source\">%@</span>\
        <a id=\"whata\" style=\"display:none\" onclick=\"gotoComment();\">&nbsp;&nbsp;<img  height=\"9px\" width=\"9px\" src=\"doc_commentCount_icon.png\" class=\"comm_img\" />\
        <span  style=\"color:#5b859e; \" id=\"upcomment\">0</span></a>\
        </div>";
        
//        self.info=@"<div class=\"tip_wrapper_parent\">\
//        <div class=\"tip_wrapper tip_wrapper_frame\"><span><b>核心提示：</b></span><span >%@</span></div></div>";
        
        self.info=@"<div id=\"top_info\" style=\"height:%fpx; width:%fpx;\">\
        #nbsp;\
        </div>";
        
        self.weidian=@"<div id=\"top_weidian\" style=\"height:%fpx; width:%fpx;\">\
        #nbsp;\
        </div>";
        
        self.video=@"<div class=\"videoSection video_frame lazy2\" data-original=\"%@\">\
        <div class=\"video_right_button\"  onclick=\"videoClick(this,%d);\"></div>\
        </div>";
        
        
        self.video_n=@"<div class=\"videoSection_noimg video_frame \" data-original=\"%@\">\
        <div class=\"video_mark\">\
        <div class=\"video_right_button\"  onclick=\"videoClick(this,%d);\"></div>\
        </div>\
        <div class=\"video_top\" ></div>\
        <div class=\"video_bottom\"></div>\
        </div>";
        
        self.note=@"<p class=\"img-note\"><small>%@</small></p>";
        
        self.slides=@"<div style=\"height:%fpx; width:100%;\" class=\"slides lazy2\"   data-original=\"%@\" onclick=\"goSlides(this);\" >\
        <div style=\"position: absolute;left:%fpx; top:%fpx\" class=\"atlas\"></div>\
        </div>";
        
        self.slides_n=@"<div style=\"height:%fpx; width:100%;\" class=\"slides_noImg \"   data-original=\"%@\" onclick=\"goSlides(this);\" >\
        <div style=\"position: absolute;left:%fpx; top:%fpx\" class=\"atlas\"></div>\
        </div>";
        
        
        
        self.tip=@"<div class=\"earlierWrapper\">\
        <div class=\"earlier_left\">&nbsp;</div>\
        <div class=\"earlier_right\">\
        <div class=\"earlier_label\">%@</div>\
        <div class=\"earlier_title\">%@</div>\
        <div class=\"earlier_time\"><span >%@</span>&nbsp;&nbsp;<span >%@</span></div>\
        <div class=\"earlier_content\">\
        %@\
        </div>\
        </div>\
        </div>";
        
        self.editorcode=@"<div class=\"editorCode\">\
        %@%@\
        <div>";
        
        self.order=[NSString stringWithFormat:@"<div style=\"height:%fpx; width:100%%;\"></div>",IFScreenFit2s(44.0) ];
        
        self.audio=[NSString stringWithFormat:@"<div id=\"audio\" style=\"height:%fpx; width:100%%;\"></div>",IFScreenFit2s(64.0) ];
        
        self.disclaimer=@"<div class=\"disclaimer\">%@</div>";
        self.originalLink=@"<div class=\"originalLink\" onclick=\"goOrigin();\">原文链接</div>";
        
        //  self.originalLink=@"<a class=\"originalLink\" href=\"%@\">原文链接</a>";
    }
    return self;
}


- (void)changeFont{
    NSString *html=[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"docTemplate" ofType:@"html"]
                                             encoding:NSUTF8StringEncoding
                                                error:nil];
    NSString *finishLog=@"doc_finish_logoIcon.png";
    
    self.htmlTemplate=[NSString stringWithFormat:html,[self divContengClass],[self noteClass],IFScreenFit2s(15.f),IFScreenFit2s(15.f),finishLog];
}


- (NSString *)divContengClass{
    NSString *divcontent=nil;
    
    
    switch ([INHtmlElementUtil sharedInstance].level) {
        case 2:
            divcontent=@"content content_middle";
            break;
        case 1:
            divcontent=@"content content_small";
            break;
            
        case 3:
            divcontent=@"content content_big";
            break;
            
        case 4:
            divcontent=@"content content_biggest";
            break;
        case 6:
            divcontent=@"content content_huge";
            break;
            
        default:
            divcontent=@"content content_middle";
            
            
    }
    
    return divcontent;
}

- (NSString *)noteClass{
    
    NSString *noteclass=nil;
    switch ([INHtmlElementUtil sharedInstance].level) {
        case 2:
            noteclass=@"img-note note_font_middle";
            break;
        case 1:
            noteclass=@"img-note note_font_small";
            break;
            
        case 3:
            noteclass=@"img-note note_font_big";
            break;
            
        case 4:
            noteclass=@"img-note note_font_biggest";
            break;
        case 6:
            noteclass=@"img-note note_font_huge";
            break;
        default:
            noteclass=@"img-note note_font_middle";
            break;
            
    }
    return noteclass;
}


@end

@implementation CLDocModel

SGR_DEF_SINGLETION(CLDocModel)


- (instancetype)init{
    self=[super init];
    if(self){
        self.needCache=[[NSMutableSet alloc] init];
    }
    return self;
}

- (void)getSlider:(NSString *)docId  uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    __weak typeof(self) me=self;
    
    [[IFCoreDataManager sharedInstance] performBlock:^(NSManagedObjectContext *moc) {
        CLItemDetail *detail=
        (CLItemDetail *)[CLItemDetail fetchWithPredict:[NSPredicate predicateWithFormat:@"itemId==%@",docId]
                                               withMOC:moc];
        if(detail){
            NSTimeInterval current=[[NSDate date] timeIntervalSince1970];
            if(fabs(current-detail.time)<=300){
                NSError *error=nil;
                NSObject *obj=[[CLGloble sharedInstance] jsonFromString:detail.json];
                if(!error){
                    sgrSafeMainThread(^{
                    
                        block(YES,obj,nil);
                    })
                    return ;
                }
            }
        }
        
        NSString *url=[NSString stringWithFormat:[self urlWithCategory:@"slider"],docId];
        
        [me getWithUrl:url param:nil
             dataBlock:^(BOOL success, id responseObj, NSError *message,NSMutableDictionary *param) {
                 if(responseObj &&
                    [responseObj isKindOfClass:[NSDictionary class]]&&
                    [@"1" isEqualToString:[responseObj sgrFGetStringForKey:@"status"]])
                 [[IFCoreDataManager sharedInstance] performBlock:^(NSManagedObjectContext *moc) {
                     NSDictionary *dic=[responseObj sgrGetDictionaryForKey:@"data"];
                     NSString *itemId=[dic sgrFGetStringForKey:@"id"];
                     CLItemDetail *detail=
                     (CLItemDetail *)[CLItemDetail managerObjByCreateOrGetWithPredicate:[NSPredicate predicateWithFormat:@"itemId==%@",docId]
                                                                                    moc:moc];
                     
                     detail.itemId=itemId;
                     detail.json=[[CLGloble sharedInstance] stringFromJson:responseObj];
                     detail.time=[[NSDate date] timeIntervalSince1970];
                     [[IFCoreDataManager sharedInstance] saveContext:moc ToPersistentStore:nil];
                     
                 }];
                 
             }
               uiBlock:^(BOOL success, id responseObj, NSError *message,NSMutableDictionary *param) {
                   
                   if(success){
                       block(success,responseObj,nil);
                   }else{
                       block(success,responseObj,@"数据错误!");
                   }
               }];
        
    }];
}

- (void)getCoverUiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    NSString *url=@"http://appv2.chanlin.org/e/app/cover.php";
    //__weak typeof(self) me=self;
    [self getWithUrl:url param:nil dataBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
        if(responseObj &&
           [responseObj isKindOfClass:[NSDictionary class]]&&
           [@"1" isEqualToString:[responseObj sgrFGetStringForKey:@"status"]]){
            NSMutableDictionary *json=[NSMutableDictionary dictionary];
            NSMutableDictionary *data=[NSMutableDictionary dictionary];
            NSMutableArray *array=[NSMutableArray array];
            NSArray *pics=[responseObj sgrGetArrayForKey:@"list"];
            for(NSDictionary *pic in pics){
                NSMutableDictionary *dic=[NSMutableDictionary dictionary];
                [dic sgrSetObject:[pic sgrGetStringForKey:@"smalltext"] forKey:@"description"];
                [dic sgrSetObject:[pic sgrGetStringForKey:@"titlepic"] forKey:@"image"];
                [array sgrAddObject:dic];
                
                
            }
            [data sgrSetObject:array forKey:@"morepic"];
            [data sgrSetObject:@"封面欣赏" forKey:@"title"];
            [json sgrSetObject:@(1) forKey:@"status"];
            [json sgrSetObject:data forKey:@"data"];
            
            [param sgrSetObject:json forKey:@"json"];
        }

    } uiBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
        if(success){
            block(success,[param sgrGetDictionaryForKey:@"json"],nil);
        }else{
            block(success,responseObj,@"数据错误!");
        }
    }];
}


-(int)getSubStringShowNumsInStringBy:(NSString*)string andSubstring:(NSString*)Substring
{
    int count =0;
    NSRange range = [string rangeOfString:Substring];
    if(range.length>0)
    {
        count++;
        while (range.length>0) {
            int startIndex =range.location+range.length;
            int endIndex = string.length -startIndex;
            string= [string substringWithRange:NSMakeRange(startIndex, endIndex)];
            range = [string rangeOfString:Substring];
            if(range.length>0)
            {
                count++;
            }
        }
    }
    return count;
}


- (NSString *)parseHTML:(CLDocEntity *)entity{
    NSMutableString *html=[IFDocTemplate sharedInstance].htmlTemplate.mutableCopy;
    if(_isStrNotNull(entity.bigpic)){
        [html replaceOccurrencesOfString:@"<!--{headImg}-->"
                              withString:[NSString stringWithFormat:[IFDocTemplate sharedInstance].headImg,(GlobleWidth*9.f)/16.f,GlobleWidth]                                 options:0
                                   range:NSMakeRange(0, html.length)];

    }
    

    NSString *title=[NSString stringWithFormat:[IFDocTemplate sharedInstance].title,_safeStr(entity.title)];
    
    [html replaceOccurrencesOfString:@"<!--{title}-->"
                          withString:title options:0 range:NSMakeRange(0, html.length)];
    
    
    NSString *time=[[INHtmlElementUtil sharedInstance] timeFormateFrom:entity.time];
    NSString *time_source=[NSString stringWithFormat:[IFDocTemplate sharedInstance].time_source,
                           _safeStr(time),_safeStr(entity.source)];
    
    [html replaceOccurrencesOfString:@"<!--{time_source}-->"
                          withString:time_source options:0 range:NSMakeRange(0, html.length)];
    
    if(_isStrNotNull(entity.smallText)){
        CGFloat height = [IFLabel2 suggestHeightOfString:entity.smallText withWidth:275.f font:[UIFont systemFontOfSize:16] lineSpace:0]+38;
        entity.smallTextHeight=height;
        
    }
    
    if(_isStrNotNull(entity.smallText) && entity.smallTextHeight>0){
      
            NSString *intro=[NSString stringWithFormat:[IFDocTemplate sharedInstance].info,entity.smallTextHeight+10.f,275.f];
            [html replaceOccurrencesOfString:@"<!--{info}-->"
                                  withString:intro options:0 range:NSMakeRange(0, html.length)];
        
    }
    
    
    

   __block  CGSize size=CGSizeZero;
    CGFloat height=0;
    if (_isStrNotNull(entity.weiDianIntro)) {
    //    int num = [self getSubStringShowNumsInStringBy:entity.weiDianIntro andSubstring:@"\n"];
        UILabel *label = [[UILabel alloc]init];
        label.numberOfLines = 0;
        label.text = entity.weiDianIntro;
        UIFont *fnt = [UIFont systemFontOfSize:13.f];
        label.font = fnt;
        
        dispatch_sync(dispatch_get_main_queue(), ^(){
            size = [label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
        });
        
        
    }
    if (_isStrNotNull(entity.weiDianUrl) && _isStrNotNull(entity.weiDianPicUrl)) {
        height = 20+(_isStrNotNull(entity.weiDianPicUrl)?entity.wdpicHeight:0)+(_isStrNotNull(entity.weiDianIntroTitle)?36:0)+(_isStrNotNull(entity.weiDianIntro)?(size.height+28):0)+32+30;
        //                height = 20+(_isStrNotNull(self.document.entity.weiDianPicUrl)?self.document.entity.wdpicHeight:0)
        //                +(_isStrNotNull(self.document.entity.weiDianIntroTitle)?36:0)+(num?(size.height+20):0);
        //                NSLog(@"====%f",(num?(size.height+20):0));
    }else
        height = 0;
    
    if(height>0){
        entity.weidianTextHeight=height;
        NSString *intro=[NSString stringWithFormat:[IFDocTemplate sharedInstance].weidian,height,275.f];
        [html replaceOccurrencesOfString:@"<!--{weidian}-->"
                              withString:intro options:0 range:NSMakeRange(0, html.length)];
    }

    if(_isStrNotNull(entity.bspic)){
        [self.needCache addObject:entity.bspic];
 
        if(_isStrNotNull(entity.surl)){
            NSMutableString *videos=@"".mutableCopy;
            [videos appendFormat:[IFDocTemplate sharedInstance].video,_safeStr(entity.bspic),0];
           // NSString *title=[dic sgrGetStringForKey:@"title"];
            if(_isStrNotNull(title)){
              //  [videos appendFormat:[IFDocTemplate sharedInstance].note,_safeStr(title)];
            }
            [html replaceOccurrencesOfString:@"<!--{video}-->"
                                  withString:videos options:0 range:NSMakeRange(0, html.length)];
            
        }else if(_isStrNotNull(entity.tjid)){
            NSMutableString *slideStr=@"".mutableCopy;
            CGFloat h1=entity.wdpicHeight;
            CGFloat left=295-IFScreenFit2s(40);
            CGFloat top=h1-IFScreenFit2s(22);

            [slideStr appendFormat:[IFDocTemplate sharedInstance].slides,h1,_safeStr(entity.bspic),left,top];
            
            [html replaceOccurrencesOfString:@"<!--{slides}-->"
                                  withString:slideStr options:0 range:NSMakeRange(0, html.length)];

            
        }
    }
    
    NSString *text=[self filterImg:entity.text];
    
    
    
    
    [html replaceOccurrencesOfString:@"<!--{text}-->"
                          withString:text options:0 range:NSMakeRange(0, html.length)];

    
    
    
    
    return html;

    
}


- (NSString *)filterImg:(NSString *)text{
    if(_isStrNULL(text)) return @"";
    NSData *data=[text dataUsingEncoding:NSUTF8StringEncoding];
    self.gifCount=0;
    unsigned long long size=[data length];
    
    const void *bytes=[data bytes];
    NSMutableData *mutableData=[[NSMutableData alloc] init];
    NSMutableData *currentData=[[NSMutableData alloc] init];
    
    BOOL isInAngleBrackets=NO;
    for(unsigned long long i=0;i<size;i++){
        unsigned char *shot=(unsigned char *)(bytes+i);
        if(((*shot)>>7)==0 && *shot=='<'){
            isInAngleBrackets=YES;
            
            currentData=[[NSMutableData alloc] init];
            
            [mutableData appendBytes:shot length:1];
            
        }else if(((*shot)>>7)==0 && *shot=='>'){
            isInAngleBrackets=NO;
            NSString *note=nil;
            [mutableData appendData:[self changeImg:currentData alt:&note]];
            [mutableData appendBytes:shot length:1];
            if(_isStrNotNull(note)){
            NSString *small=[NSString stringWithFormat:@"<small class=\"%@\">%@</small>",[[IFDocTemplate sharedInstance] noteClass],note];
                [mutableData appendData:[small dataUsingEncoding:NSUTF8StringEncoding]];
            }
            
        }else{
            if(isInAngleBrackets){
                [currentData appendBytes:shot length:1];
            }else{
                [mutableData appendBytes:shot length:1];
            }
        }
    }
    if(self.gifCount>2){
        self.loadLevel=3;
    }else if(self.imageArray.count>8){
        self.loadLevel=2;
    }
    
    return [[NSString alloc] initWithData:mutableData encoding:NSUTF8StringEncoding];
    
    
}

- (NSData *)changeImg:(NSData *)data alt:(NSString * __autoreleasing *)note{
    if(data==nil) return nil;
    
    NSString *tag=[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] trim];
    
    if([tag hasPrefix:@"img"] || [tag hasPrefix:@"IMG"]){
        NSString *url=[self srcUrlFromImg2:[tag dataUsingEncoding:NSUTF8StringEncoding]];
        
        BOOL lazy=YES;
        if(_isStrNotNull(url)){
            [self.needCache addObject:url];
            if([url hasSuffix:@"gif"]){
                _gifCount++;
                lazy=YES;
            }
        }else{
            return [@"/" dataUsingEncoding:NSUTF8StringEncoding];
        }
        
        
        
        [self.imageArray sgrAddObject:url];
        
        //NSDictionary *sizeDic=[self.imgs sgrGetDictionaryForKey:url];
        CGFloat h=IMAGE_HEIGHT_DEFAULT;
        CGFloat w1=0;
        CGFloat h1=0;
        NSRange range=[tag rangeOfString:@"width=\""];
        if(range.location!=NSNotFound){
            NSUInteger start=range.location+range.length;
            NSRange range2=[tag rangeOfString:@"\"" options:0 range:NSMakeRange(start, tag.length-start)];
            w1=[[tag substringWithRange:NSMakeRange(start, range2.location-start)] floatValue];
            
        }
        
         range=[tag rangeOfString:@"height=\""];
        if(range.location!=NSNotFound){
            NSUInteger start=range.location+range.length;
            NSRange range2=[tag rangeOfString:@"\"" options:0 range:NSMakeRange(start, tag.length-start)];
            h1=[[tag substringWithRange:NSMakeRange(start, range2.location-start)] floatValue];
            
        }
        
        range=[tag rangeOfString:@"alt=\""];
        NSString *alt=nil;
        if(range.location!=NSNotFound){
            NSUInteger start=range.location+range.length;
            NSRange range2=[tag rangeOfString:@"\"" options:0 range:NSMakeRange(start, tag.length-start)];
            alt=[tag substringWithRange:NSMakeRange(start, range2.location-start)];
            if(_isStrNotNull(alt)) *note=alt;
            
        }

        NSString *imgStyle=nil;
        
        if(w1!=0 && h1!=0){
            h=(h1/w1*(I_DOC_CONTENT_WIDTH));
            imgStyle=[NSString stringWithFormat:@"height=\"%fpx\" width=\"%fpx\"",h,I_DOC_CONTENT_WIDTH];
            
        }else{
            h=IMAGE_HEIGHT_DEFAULT;
            imgStyle=[NSString stringWithFormat:@"style=\"max-height:%fpx; max-width:%fpx;\"",IMAGE_HEIGHT_DEFAULT,I_DOC_CONTENT_WIDTH];
        }
        NSString *img=nil;

        
        
        if(lazy){
            img=[NSString stringWithFormat:@"div class=\"img_p\"  style=\"height:%fpx; width:100%%; text-align:center;\"   data-original=\"%@\" onclick=\"showPic(this);\" ><img %@ class=\"lazy_img lazy\"  data-original=\"%@\" /></div",h,_safeStr(url),imgStyle,_safeStr(url)];
        }else{
            img=[NSString stringWithFormat:@"div class=\"img_p\"  style=\"height:%fpx; width:100%%;text-align:center;\"   data-original=\"%@\" onclick=\"showPic(this);\" ><img  %@ class=\"lazy_img\"  src=\"%@\" /></div",h,_safeStr(url),imgStyle,_safeStr(url)];
        }
        return [img dataUsingEncoding:NSUTF8StringEncoding];
        
    }else if([tag hasPrefix:@"a"] || [tag hasPrefix:@"A"]){
        NSString *a=[tag stringByAppendingString:@" onclick=\"dispatchLink(this)\""];
        return [a dataUsingEncoding:NSUTF8StringEncoding];
    }else {
        return data;
    }
    
    return nil;
}

- (NSString *)srcUrlFromImg2:(NSData *)imgData{
    unsigned long long start=0;
    unsigned long long end=0;
    
    unsigned long long m=[imgData length];
    
    const void *bytes=[imgData bytes];
    
    BOOL isInString=NO;
    BOOL isSrc=NO;
    BOOL isEqual=NO;
    
    for(unsigned long long i=0;i<m;i++){
        
        unsigned char *shot=(unsigned char *)(bytes+i);
        
        if(((*shot)>>7)==0 &&((*shot)=='"' || (*shot)=='\'')&& (i>0 && *((unsigned char *)(bytes+i-1))!='\\') ){
            
            isInString=!isInString;
            if(isEqual){
                if(isInString)
                    start=i;
                else{
                    end=i;
                    isSrc=NO;isEqual=NO;
                    if(start!=0 && end!=0) break;
                }
            }
            continue;
        }
        
        if(!isInString){
            if(((*shot)>>7)==0 &&
               i>3 &&
               
               (((*shot)=='c' &&
                 *((unsigned char *)(bytes+i-1))=='r' &&
                 *((unsigned char *)(bytes+i-2))=='s') ||
                ((*shot)=='C' &&
                 *((unsigned char *)(bytes+i-1))=='R' &&
                 *((unsigned char *)(bytes+i-2))=='S')
                
                
                ) &&
               *((unsigned char *)(bytes+i-3))==' '){
                isSrc=YES;
                continue;
            }
            
            if(isSrc){
                if((*shot)=='='){
                    isEqual=YES;
                }else if((*shot)!=' '){
                    isSrc=NO;isEqual=NO;
                }
            }
            
        }
    }
    
    if(start==0 || end==0){
        return nil;
    }else{
        NSData *subData= [imgData subdataWithRange:NSMakeRange(start+1, (end-start-1))];
        return  [[NSString alloc] initWithData:subData encoding:NSUTF8StringEncoding];
    }
    
}


- (void)getDoc:(NSString *)docId  uiBlock:(void (^)(BOOL success,CLDocEntity* responseObj,NSString *message) )block{
    __weak typeof(self) me=self;
   // [[IFCoreDataManager sharedInstance] performBlock:^(NSManagedObjectContext *moc){
        NSString *url=[NSString stringWithFormat:[self urlWithCategory:@"slider"],docId];
   
        [me getWithUrl:url param:nil
             dataBlock:^(BOOL success, id responseObj, NSError *message,NSMutableDictionary *param) {
                 if(responseObj &&
                    [responseObj isKindOfClass:[NSDictionary class]]&&
                    [@"1" isEqualToString:[responseObj sgrFGetStringForKey:@"status"]]){
                     CLDocEntity *entity=[CLDocEntity new];
                     NSDictionary *datadic=[responseObj sgrGetDictionaryForKey:@"data"];
                     entity.title=[datadic sgrGetStringForKey:@"title"];
                     entity.itmeId=[datadic sgrGetStringForKey:@"id"];
                     entity.smallText = [datadic sgrGetStringForKey:@"smalltext"];
                     entity.smallTextTitle = [datadic sgrGetStringForKey:@"smalltext_title"];
                     
                     
                     entity.time=[[datadic sgrFGetStringForKey:@"newstime"] longLongValue];
                     entity.shareUrl=[datadic sgrGetStringForKey:@"shareurl"];
                     entity.relation=[datadic sgrGetArrayForKey:@"relation"];
               
                     
                     entity.weiDianPicUrl = [datadic sgrGetStringForKey:@"wdpic"];
                     entity.weiDianPicH = [datadic sgrGetNumberForKey:@"wdpic_h"];
                     entity.weiDianPicW = [datadic sgrGetNumberForKey:@"wdpic_w"];
                     entity.weiDianBtnImgUrl = [datadic sgrGetStringForKey:@"wdbutton"];
                     entity.weiDianIntroTitle = [datadic sgrGetStringForKey:@"wdtitle"];
                     entity.weiDianIntro = [datadic sgrGetStringForKey:@"wdintro"];
                     entity.weiDianUrl = [datadic sgrGetStringForKey:@"wdlink"];
                     entity.sharepicUrl = [datadic sgrGetStringForKey:@"sharepic"];
                     entity.bigpic=[datadic sgrGetStringForKey:@"bigpic"];
                     entity.bspic=[datadic sgrGetStringForKey:@"bspic"];
                     entity.vurl=[datadic sgrGetStringForKey:@"vurl"];
                     entity.surl=[datadic sgrGetStringForKey:@"surl"];
                     entity.tjid=[datadic sgrGetStringForKey:@"tjid"];
                     entity.source=[datadic sgrGetStringForKey:@"writer"];
                     entity.audio=[datadic sgrGetStringForKey:@"audio"];
                     entity.text=[datadic sgrGetStringForKey:@"newstext"];
                     
                  
                    // NSString *text=[datadic sgrGetStringForKey:@"newstext"];
                     entity.dic=[datadic sgrGetDictionaryForKey:@"befrom"];
                     float wdw=[[datadic sgrGetNumberForKey:@"wdpic_w"] floatValue];
                     float wdh=[[datadic sgrGetNumberForKey:@"wdpic_h"] floatValue];
                     if(wdw==0 || wdh==0){
                         entity.wdpicHeight=180.f;
                     }else{
                         entity.wdpicHeight=295*(wdh/wdw);
                     }
                     
                     
                     entity.html=[self parseHTML:entity];
//                     entity.elements=[CLHtmlExtracter parse:[NSString stringWithFormat:@"<html>%@</html>",text]];
//                     if(_isStrNotNull(entity.bspic)){
//                         NSMutableArray *array=[NSMutableArray arrayWithCapacity:entity.elements.count+1];
//                         INHtmlElement *element=[[INHtmlElement alloc] init];
//                         [array sgrAddObject:element];
//                         element.type=HtmlElementTypeGallery;
//                         
//                         element.strValue=entity.bspic.mutableCopy;
//                         element.linkUrl=_isStrNULL(entity.surl)?entity.tjid:entity.surl;
//                         [array addObjectsFromArray:entity.elements];
//                         entity.elements=array;
//                     }
                     [param sgrSetObject:entity forKey:@"entity"];
                     
                 }
             }
               uiBlock:^(BOOL success, id responseObj, NSError *message,NSMutableDictionary *param) {
                   if(success){
                       block(success,[param sgrGetType:[CLDocEntity class] forKey:@"entity"],nil);
                   }else{
                       block(success,nil,@"数据错误!");
                   }
               }];
   // }];
}

- (void)linkElementText:(CLDocEntity *)entity{
    //self.attributeString=[[NSMutableAttributedString alloc] init];
    
}

@end
